/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package peterka.ecka;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Vector;
import peterka.ecka.commons.Utils;
import peterka.ecka.model.EItem;

/**
 *
 * @author mpeterka
 */
public class DataReader {

    /**
     *
     * @return List of {@link EItem}s.
     */
    public Vector read() {
        try {
            return load("data.txt");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    protected static EItem parseLine(String[] line) {
        //kod | nazev | skore nebezp |bezpecna | zdravi skodliva | zivocich | ne deti | alergie | zakazana |
        EItem eItem = new EItem();
        eItem.setCode(line[0]);
        eItem.setName(line[1]);
        eItem.setDangerScore(parseInt(line[2]));
        eItem.setSafe(parseBoolean(line[3]));
        eItem.setHealthDanger(parseBoolean(line[4]));
        eItem.setAnimal(parseBoolean(line[5]));
        eItem.setNoChild(parseBoolean(line[6]));
        eItem.setAllergy(parseBoolean(line[7]));
        eItem.setBanned(parseBoolean(line[8]));
        return eItem;
    }

    protected static boolean parseBoolean(String input) {
        if ("1".equals(input)) {
            return true;
        }
        return false;
    }

    protected static int parseInt(String input) {
        return Integer.parseInt(input);
    }

    protected Vector load(String resName) throws IOException {
        final String DELIMITER = "|";
        Vector vector = new Vector();
        InputStream in = getClass().getResourceAsStream(resName);

        try {
            DataInputStream din = new DataInputStream(in);
            Reader rin = new InputStreamReader(in);
            String line = null;
            while ((line = readLine(rin)) != null) {
                String[] splitted = Utils.split(line, DELIMITER);
                EItem eItem = parseLine(splitted);
                vector.addElement(eItem);
            }

        } finally {
            in.close();
        }
        return vector;
    }

    private String readLine(Reader in) throws IOException {
        // This is not efficient.
        StringBuffer line = new StringBuffer();
        int i;
        while ((i = in.read()) != -1) {
            char c = (char) i;
            if (c == '\n') {
                break;
            }
            if (c == '\r'); else {
                line.append(c);
            }
        }
        if (line.length() == 0) {
            return null;
        }
        return line.toString();
    }
}
